import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '@/api/auth'
import { useUserStore } from '@/store/user'

export default function useLoginLogic() {
  const router = useRouter()
  const userStore = useUserStore()
  const loginForm = ref(null)
  const loading = ref(false)

  const form = reactive({
    username: '',
    password: ''
  })

  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' }
    ]
  }

  const handleLogin = async () => {
    if (!loginForm.value) return
    try {
      await loginForm.value.validate()
      loading.value = true
      
      // 发送登录请求
      const response = await login(form)
      const { data } = response
      
      // 保存用户信息
      userStore.setUserInfo({
        token: data.token,
        username: data.username,
        role: data.role
      })
      
      ElMessage.success('登录成功')
      
      // 根据角色跳转到不同页面
      if (data.role === 'teacher') {
        router.push('/teacher/activities')
      } else {
        router.push('/student/sign-in')
      }
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error(error?.response?.data?.message || error.message || '登录失败')
    } finally {
      loading.value = false
    }
  }

  const handleRegister = () => {
    router.push('/register')
  }

  return {
    loginForm,
    loading,
    form,
    rules,
    handleLogin,
    handleRegister
  }
} 